package deepbrain.simnetwork.loader;

import java.util.Set;

import deepbrain.simnetwork.exception.SimNetworkException;
import deepbrain.simnetwork.exception.SimNetworkRuntimeException;
import deepbrain.simnetwork.factory.NetworkStateFactory;
import deepbrain.simnetwork.mechanism.Mechanism;
import deepbrain.simnetwork.network.Network;
import deepbrain.simnetwork.structure.Connection;

/**
 * 
 * 
 * @author Li Yang
 * @create 2009-2-24
 */
public class NetworkLoaderImpl implements NetworkLoader {

	protected int numOfNodes;
	protected NetworkStateFactory nodesFactory;
	protected ConnectionsLoader connectionsLoader;

	public NetworkLoaderImpl() {
	}

	public NetworkLoaderImpl(int numOfNodes) {
		this.numOfNodes = numOfNodes;
	}

	public NetworkLoaderImpl(int numOfNodes, NetworkStateFactory nodesFactory) {
		this.numOfNodes = numOfNodes;
		this.nodesFactory = nodesFactory;
	}

	public NetworkLoaderImpl(int numOfNodes, NetworkStateFactory nodesFactory,
			ConnectionsLoader connectionsLoader)
			throws SimNetworkRuntimeException {
		if (nodesFactory == null)
			throw new SimNetworkRuntimeException("Node Factory is Null!");
		if (connectionsLoader == null)
			throw new SimNetworkRuntimeException("Node Factory is Null!");

		this.numOfNodes = numOfNodes;
		this.nodesFactory = nodesFactory;
		this.connectionsLoader = connectionsLoader;
	}

	public void setNumOfNodes(int numOfNodes) {
		this.numOfNodes = numOfNodes;
	}

	public void setNodesFactory(NetworkStateFactory nodesFactory) {
		this.nodesFactory = nodesFactory;
	}

	public void setConnectionsLoader(ConnectionsLoader connectionsLoader) {
		this.connectionsLoader = connectionsLoader;
	};

	public Network loadNetwork() throws SimNetworkException {
		if (nodesFactory == null)
			throw new SimNetworkException(
					"The NodesFactory is Null Before Loading Network.");
		if (connectionsLoader == null)
			throw new SimNetworkException(
					"The ConnectionsLoader is Null Before Loading Network.");

		Set<Connection<?>> connections = connectionsLoader
				.loadConnections(numOfNodes);
		Mechanism[] mechanisms = connectionsLoader.loadMechanisms(numOfNodes);
		Network network = new Network(numOfNodes, connections);
		if (mechanisms!=null) {
			network.setMechanisms(mechanisms);
		}
		return network;
	}

}
